package com.richapp.launcher.serialport.gateway.command;

import android.util.Log;

import com.jack.util.bytes.ByteUtil;
import com.jack.util.hex.HexUtil;
import com.richapp.launcher.serialport.gateway.ControlInstructionMessage;
import com.richapp.launcher.serialport.gateway.GatewayServer;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.net.util.HexTool;

import java.util.ArrayList;
import java.util.List;

public class InfraredControlCmd extends BasicCommand {

	private static byte[] endbytes = null;

	private static InfraredControlCmd resetCmd = null;


	private InfraredControlCmd() {
		endbytes = new byte[]{(byte)0xA5,0x5A,0x5A};
	}
	
	public static InfraredControlCmd getInstance(){
		if(resetCmd == null){
			resetCmd = new InfraredControlCmd();
		}
		return resetCmd;
	}

	public void controlCmd(String cpuBoxId,String deviceId, String deviceNumber,String way,byte[] data,String controlKey){
		this.PacketHead = "FF001800";
		this.ID = deviceId;
		this.Number = deviceNumber;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationControlCMD(data));
		cim.setKey(controlKey);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_CONTROL);
		GatewayServer.getInstance().writeMessage(cim);
	}

	public void controlCmd2(String cpuBoxId,String deviceId, String deviceNumber,String way,byte[] data,String controlKey,byte[] lengthBytes,byte deviceType){
		this.PacketHead = "FF001800";
		this.ID = deviceId;
		this.Number = deviceNumber;
		ControlInstructionMessage cim = new ControlInstructionMessage(cpuBoxId,deviceId,deviceNumber,way);
		cim.setHexInstruction(combinationControlCMD2(data,lengthBytes,deviceType,HexUtil.HexToByte(deviceId)));
		cim.setKey(controlKey);
		cim.setInstructionFlag(GatewaytConstant.INSTRUCTION_FLAG_INFRARED_CONTROL);
		GatewayServer.getInstance().writeMessage(cim);
	}

	/**
	 * 不组包
	 * @param data
	 * @return
     */
	private String combinationControlCMD(byte[] data){
		String cmd = PacketHead+ID+Number+"00000000000000000000";
		String checkCode = HexUtil.sumCheck(cmd);
		return cmd+checkCode+HexUtil.getCombindData(data);
	}

	/**
	 * 组包
	 * @param data
	 * @return
     */
	private String combinationControlCMD2(byte[] data,byte[] lengthBytes,byte deviceType,byte deviceId){
		String cmd = PacketHead+ID+Number+"00000000000000000000";
		String checkCode = HexUtil.sumCheck(cmd);
		return cmd+checkCode+HexUtil.getCombindData2(data,lengthBytes,deviceType,deviceId);
	}

	@Override
	public void analyticalCmd(String cmd) {

	}

	@Override
	public void analyticalInfrared(ControlInstructionMessage message) {
		Log.v(getClass().getName(), "收到红外控制结果"+message);
	}
}
